package com.qingkai.onlineshop.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.qingkai.onlineshop.data.dao.BannerDao
import com.qingkai.onlineshop.data.dao.CategoryDao
import com.qingkai.onlineshop.data.dao.ItemDao
import com.qingkai.onlineshop.data.dao.PicUrlDao
import com.qingkai.onlineshop.data.entity.BannerEntity
import com.qingkai.onlineshop.data.entity.CategoryEntity
import com.qingkai.onlineshop.data.entity.ItemEntity
import com.qingkai.onlineshop.data.entity.PicUrlEntity

@Database(entities = [
    BannerEntity::class,
    CategoryEntity::class,
    ItemEntity::class,
    PicUrlEntity::class
], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun bannerDao(): BannerDao
    abstract fun categoryDao(): CategoryDao
    abstract fun itemDao(): ItemDao
    abstract fun picUrlDao(): PicUrlDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        private const val DATABASE_NAME = "database.db"

        fun getInstance(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                DATABASE_NAME
            ).createFromAsset(DATABASE_NAME)
                .build()
        }
    }
}